﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Globalization;
using System.Windows.Forms;
using gtasks.Model.Convert;
using pub.NET20Fix;
using todo;
using todo.Model;
using todo.Persistence;

namespace gtasks
{
    internal partial class SaveTasklistForm : Form
    {
        public string FilePath { get; set; }
        public TodoList TodoList { get; set; }
        public volatile bool Canceled;
        public Dictionary<string, string> NewIdMap { get; private set; }

        private string _taskListTitle;
        private int _progressCounter;
        private string _progressStatus;

        private BackgroundWorker _worker;
        private Synchronizer _synchronizer;


        public SaveTasklistForm()
        {
            InitializeComponent();
            this.Font = SystemFonts.DialogFont;
            Canceled = true;
#if zh
            this.Text = "Google 任务";
#endif
        }

        private void SaveTasklistForm_Shown(object sender, EventArgs e)
        {
            Upload();
        }

        private void Upload()
        {
            var pos1 = FilePath.IndexOf(')') + 1;
            var pos2 = FilePath.LastIndexOf('.');
            _taskListTitle = FilePath.Substring(pos1, pos2 - pos1);
            _progressStatus = "Submitting changes of {0}";
#if zh
            _progressStatus = "正在提交 {0} 的修改";
#endif

            _worker = new BackgroundWorker();
            _worker.WorkerSupportsCancellation = true;
            _worker.WorkerReportsProgress = true;
            _synchronizer = new Synchronizer();
            _synchronizer.OnException += Synchronizer_OnException;

            _worker.DoWork += (sender, args) => _synchronizer.Sync(FilePath, TodoList);
            _worker.RunWorkerCompleted += (sender, args) => {
                if (args.Error != null)
                {
                    App.OnUnknownException(args.Error);
                }

                NewIdMap = new Dictionary<string, string>();
                foreach (var kvp in _synchronizer.NewIdMap)
                {
                    NewIdMap[kvp.Key.ToString(CultureInfo.InvariantCulture)] = kvp.Value;
                }

                _worker = null;
                this.Close();
            };
            _worker.RunWorkerAsync();
        }

        void Synchronizer_OnException(Exception e)
        {
            App.OnUnknownException(e);
            this.Close();
        }

        private void timerOpening_Tick(object sender, EventArgs e)
        {
            var text = string.Format(_progressStatus, _taskListTitle);
            text += new string('.', (++_progressCounter % 3) + 1);
            lblProgress.Text = text;
            lblProgress.Visible = true;
        }

        private void SaveTasklistForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(_worker != null)
            {
                _synchronizer.AbortProcessing();
                _worker.CancelAsync();
            }
        }
    }
}